public class SortColor {
    //arr[0...zero] 存放红色0， arr[zero+1...i-1]存放白色，arr[two,nums.length-1]存放蓝色
    public void sortColors(int[] nums) {
        int zero = -1, i = 0, two = nums.length;
        while (i < two) {
            if (nums[i] == 0) {//红色
                zero++;
                swap(nums, zero, i);
                i++;
            } else if (nums[i] == 2) {//蓝色
                two--;
                swap(nums, two, i);
            } else {
                i++;
            }
        }
    }

    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }

    public void printArr(int[] nums) {
        for (int i = 0; i < nums.length; i++) {
            System.out.print(nums[i]);
            if (i < nums.length - 1) {
                System.out.print(",");
            }
        }
        System.out.println();
    }

    public static void main(String[] args) {
        int[] nums = new int[]{2, 0, 2, 1, 1, 0};
        SortColor sortColor = new SortColor();
        sortColor.printArr(nums);

        sortColor.sortColors(nums);
        sortColor.printArr(nums);

    }
}
